package com.ruoyi.business.service;

import com.ruoyi.business.domain.MonitoringEnergy;
import com.ruoyi.business.mapper.MonitoringEnergyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 能源数据处理服务
 *
 * @author qiancheng
 * @date 2025-09-06
 */
@Service
public class S7EnergyDataService {

    @Autowired
    private MonitoringEnergyMapper energyMapper;

    // 用于存储上次采集的累计值，避免重复累加
    private final Map<String, BigDecimal> lastValues = new HashMap<>();

    // 数据采集间隔(秒)，应与定时任务间隔保持一致
    private final int ACQUISITION_INTERVAL = 30;

    /**
     * 处理PLC读取到的数据并保存到数据库
     * @param plcIp PLC设备IP
     * @param variableName 变量英文名称
     * @param value 读取到的当前值
     */
    public void processPlcData(String plcIp, String variableName, BigDecimal value) {
        // 处理天然气数据
        if ("mildMildfurnactu8".equals(variableName) && "192.168.0.1".equals(plcIp)) {
            handleEnergyData(value, "天然气","天然气");
        }
        // 处理喷淋主管水流量
        else if ("waterCoolActualfloww".equals(variableName) && "192.168.0.1".equals(plcIp)) {
            handleEnergyData(value, "水","主管水");
        }
        // 处理喷淋旁通水流量
        else if ("waterCoolActualflows".equals(variableName) && "192.168.0.1".equals(plcIp)) {
            handleEnergyData(value, "水","旁通水");
        }
    }

    /**
     * 处理能源数据并保存到数据库
     */
    private void handleEnergyData(BigDecimal currentValue, String energyName,String remark) {
        // 计算当前间隔的使用量 = 当前值 * 采集间隔
        BigDecimal intervalUsage = currentValue.multiply(new BigDecimal(ACQUISITION_INTERVAL));

        // 获取当前日期
        LocalDate now = LocalDate.now();
        int year = now.getYear();
        int month = now.getMonthValue();
        int day = now.getDayOfMonth();

        // 查询当天该能源的记录
        MonitoringEnergy todayRecord = energyMapper.selectByDateAndName(
                year, month, day, energyName,remark);

        if (todayRecord != null) {
            // 已有记录，累加使用量
            //BigDecimal totalUsage = todayRecord.getEnergyUsage().add(intervalUsage);
            todayRecord.setEnergyUsage(currentValue);
            energyMapper.updateById(todayRecord);
        } else {
            // 无记录，创建新记录
            MonitoringEnergy newRecord = new MonitoringEnergy();
            newRecord.setRecordYear((long) year);
            newRecord.setRecordMonth((long) month);
            newRecord.setRecordDay((long) day);
            newRecord.setEnergyName(energyName);
            newRecord.setEnergyUsage(currentValue);
            newRecord.setRemark(remark);
            energyMapper.insert(newRecord);
        }

        // 保存当前值用于下次计算（如果需要基于差值计算）
        lastValues.put(energyName, currentValue);
    }
}
